package com.mantru.iotpot.dishes;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;


import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.DateClass.BoxDate;

import com.mantru.iotpot.R;
import com.mantru.iotpot.Tools.tools;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.DishesRecordEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class DishesRecordSetActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout back;
    private EditText food_name;
    private ConstraintLayout food_num_box;
    private EditText food_weight;
    private EditText box_name1;
    private EditText box_name2;
    private EditText box_name3;
    private EditText box_name4;
    private EditText box_weight1;
    private EditText box_weight2;
    private EditText box_weight3;
    private EditText box_weight4;
    private Button next;
    private TextView food_num;
    private ApplicationClass ac;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dishes_record_set);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        initialization();//初始化控件
        setEdittextListener();
    }

    //初始化控件
    private void initialization(){
        back = findViewById(R.id.dishes_record_set_back);//返回按钮
        food_name = findViewById(R.id.dishes_record_set_name);//菜谱名称
        food_num_box = findViewById(R.id.adapter_dishes_set_num);
        food_num = findViewById(R.id.adapter_dishes_set_num_textview);//菜品份数
        food_weight = findViewById(R.id.adapter_dishes_set_weight_editText);//菜品重量
        box_name1 = findViewById(R.id.adapter_dishes_set_box_name1);//菜盒材料名
        box_name2 = findViewById(R.id.adapter_dishes_set_box_name2);
        box_name3 = findViewById(R.id.adapter_dishes_set_box_name3);
        box_name4 = findViewById(R.id.adapter_dishes_set_box_name4);
        box_weight1 = findViewById(R.id.adapter_dishes_set_box_weight1);//菜盒材料重量
        box_weight2 = findViewById(R.id.adapter_dishes_set_box_weight2);
        box_weight3 = findViewById(R.id.adapter_dishes_set_box_weight3);
        box_weight4 = findViewById(R.id.adapter_dishes_set_box_weight4);
        next = findViewById(R.id.adapter_dishes_set_next);//下一步按钮
        back.setOnClickListener(this);
        next.setOnClickListener(this);
        food_num_box.setOnClickListener(this);
    }

    private void setEdittextListener(){
        food_name.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        food_weight.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_name1.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_name2.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_name3.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_name4.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_weight1.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_weight2.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_weight3.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });

        box_weight4.setOnEditorActionListener((v, actionId, event) -> {
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || actionId == EditorInfo.IME_ACTION_NEXT
                    || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入法管理器
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                // 隐藏软键盘
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.dishes_record_set_back){//点击返回
            finish();
        }else if (v.getId() == R.id.adapter_dishes_set_next){//点击下一步按钮
            tools.hideKeyboard(DishesRecordSetActivity.this);
            check();//检查用户输入的数据
        } else if (v.getId() == R.id.adapter_dishes_set_num) {//选择份数
            showPortionDialog();
        }
    }

    //显示选择份数的弹窗
    private void showPortionDialog() {
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择份数");
        // 生成 1-3 份的选项
        String[] portions = new String[3];
        for (int i = 0; i < 3; i++) {
            portions[i] = (i + 1) + "份";
        }
        // 设置选项
        builder.setItems(portions, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 更新份数显示
                food_num.setText((which + 1) + "份");
            }
        });
        // 显示对话框
        builder.show();
    }

    //一个用于检查用户输入内容的方法
    private void check(){
        String name = food_name.getText().toString();
        String num = food_num.getText().toString().replace("份", "");
        String weight = food_weight.getText().toString();
        String bname1 = box_name1.getText().toString();
        String bname2 = box_name2.getText().toString();
        String bname3 = box_name3.getText().toString();
        String bname4 = box_name4.getText().toString();
        String Bname[] = {bname1,bname2,bname3,bname4};
        String bweight1 = box_weight1.getText().toString();
        String bweight2 = box_weight2.getText().toString();
        String bweight3 = box_weight3.getText().toString();
        String bweight4 = box_weight4.getText().toString();
        String Bweight[] = {bweight1,bweight2,bweight3,bweight4};
        if (name.isEmpty()){
            //Toast.makeText(this, "请输入菜谱名称", Toast.LENGTH_SHORT).show();
            ToastUtils.show(this, "请输入菜谱名称");
        } else if (weight.isEmpty()) {
            //Toast.makeText(this, "请输入菜谱重量", Toast.LENGTH_SHORT).show();
            ToastUtils.show(this, "请输入菜谱重量");
        } else {
            boolean result = ac.GetSQLData_VegetableAndSpec_IsExists(0,name,Integer.parseInt(num));
            // 检查数据是否连续
            boolean[] hasData = {
                    !bname1.isEmpty() && !bweight1.isEmpty(),
                    !bname2.isEmpty() && !bweight2.isEmpty(),
                    !bname3.isEmpty() && !bweight3.isEmpty(),
                    !bname4.isEmpty() && !bweight4.isEmpty()
            };
            boolean isValid = true;
            // 检查是否有数据不连续的情况
            for (int i = 1; i < hasData.length; i++) {
                if (hasData[i] && !hasData[i - 1]) { // 当前有数据但前一个没有数据
                    isValid = false;
                    break;
                }
            }
            if (!isValid) {
                //Toast.makeText(this, "请按顺序填写菜盒内容", Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "请按顺序填写菜盒内容");
            }else {
                if (!bname2.isEmpty() && bweight2.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒2投放材料的重量", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒2投放材料的重量");
                } else if (bname2.isEmpty() && !bweight2.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒2投放材料名称", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒2投放材料名称");
                } else if (!bname3.isEmpty() && bweight3.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒3投放材料的重量", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒3投放材料的重量");
                } else if (bname3.isEmpty() && !bweight3.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒3投放材料名称", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒3投放材料名称");
                } else if (!bname4.isEmpty() && bweight4.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒4投放材料的重量", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒4投放材料的重量");
                } else if (bname4.isEmpty() && !bweight4.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒4投放材料名称", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒4投放材料名称");
                }else if (!bname1.isEmpty() && bweight1.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒4投放材料的重量", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒1投放材料的重量");
                } else if (bname1.isEmpty() && !bweight1.isEmpty()) {
                    //Toast.makeText(this, "请输入菜盒4投放材料名称", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(this, "请输入菜盒1投放材料名称");
                }else {
                    if (!result){
                        List<BoxDate> handingConfigs = new ArrayList<>();
                        for (int i = 0;i < 4;i++){
                            if (Bweight[i].isEmpty()){
                                Bweight[i] = "0";
                            }
                            BoxDate handingConfig = new BoxDate(String.valueOf(i+1),Bname[i],Bweight[i]);
                            Log.d("DishesRecordSetActivity","box_index: " + String.valueOf(i+1) + " material_name: " + Bname[i] +" weight: " +Bweight[i]);
                            handingConfigs.add(handingConfig);
                        }
                        DishesRecordEvent event = new DishesRecordEvent(
                                name,
                                num,
                                weight,
                                handingConfigs
                        );
                        // 发布粘性事件
                        EventBus.getDefault().postSticky(event);
                        // 如果所有检查通过，可以继续下一步
                        Intent intent = new Intent(this, DishesRecordActivity.class);
                        intent.putExtra("food_name",name);
                        intent.putExtra("food_num",num);
                        startActivity(intent);
                        finish();
                    }else {
                        //Toast.makeText(this, "菜品名称已存在，请重新输入", Toast.LENGTH_SHORT).show();
                        ToastUtils.show(this, "菜品名称已存在，请重新输入");
                    }
                }
            }
        }
    }
}